package com.ktjy.controller;


import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.annotation.Excel;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.ktjy.dto.CourseDTO;
import com.ktjy.dto.PostDTO;
import com.ktjy.dto.UserDTO;
import com.ktjy.pojo.SysPost;
import com.ktjy.pojo.SysUser;
import com.ktjy.pojo.TbCourse;
import com.ktjy.service.ISysPostService;
import com.ktjy.service.ITbCourseService;
import com.ktjy.utils.AjaxResult;
import com.ktjy.utils.ExcelUtil;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.poi.ss.formula.functions.T;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

/**
 * <p>
 * 课程管理 前端控制器
 * </p>
 *
 * @author jjx
 * @since 2025-08-02
 */
@RestController
@RequestMapping("/api/tb/course")
public class TbCourseController {
    Logger log = LoggerFactory.getLogger(TbCourseController.class);

    @Autowired
    ITbCourseService courseService;

    @PreAuthorize("@ss.hasPerm('clues:course:list')")
    @GetMapping("/list")
    public AjaxResult list(CourseDTO courseDTO,
                           @RequestParam(value = "pageNo", defaultValue = "1") Integer pageNo,
                           @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize) {
        IPage<TbCourse> page = courseService.findPage(courseDTO, pageNo, pageSize);
        return AjaxResult.success(page);
    }

    @PostMapping("/save")
    @PreAuthorize("@ss.hasPerm('clues:course:add') or @ss.hasPerm('clues:course:edit')")
    public AjaxResult saveOrUpdate(@RequestBody TbCourse tbCourse) {
        try {
            if (tbCourse.getId() == null) {
                String lowerCase = RandomStringUtils.randomAlphanumeric(8).toLowerCase(); //课程编号
                tbCourse.setCode(lowerCase);
            }
            boolean ok = courseService.saveOrUpdate(tbCourse);
            if (ok) {
                return AjaxResult.success("保存成功");
            }
        } catch (Exception e) {
            log.error("TbCourseController中saveOrUpdate方法执行报错的。", e);
        }
        return AjaxResult.error("保存失败");
    }

    @PreAuthorize("@ss.hasPerm('clues:course:query') or @ss.hasPerm('clues:course:edit')")
    @GetMapping("/view/{id}")
    public AjaxResult view(@PathVariable("id") Long id) {
        //查询详情
        try {
            TbCourse tbCourse = courseService.getById(id);
            if (tbCourse != null) {
                return AjaxResult.success(tbCourse);
            }
        } catch (Exception e) {
            log.error("TbCourseController中view方法执行报错的。", e);
        }
        return AjaxResult.error();
    }

//    @DeleteMapping("/del/{id}")
//    public AjaxResult del(@PathVariable("id") Long id){
//        try {
//            boolean ok= courseService.removeById(id);
//            if(ok){//删除成功
//                return AjaxResult.success("删除成功");
//            }
//        } catch (Exception e) {
//            log.error("TbCourseController中del方法执行报错的。",e);
//        }
//        return AjaxResult.error("删除失败");
//    }

    /**
     * 批量删除课程
     *
     * @param ids 课程ID数组
     * @return 删除结果
     */
    @PreAuthorize("@ss.hasPerm('clues:course:remove')")
    @DeleteMapping("/batchDel")
    public AjaxResult batchDelete(@RequestBody(required = false) List<Long> ids) {
        // 参数校验
        if (ids == null || ids.isEmpty()) {
            return AjaxResult.error("请选择要删除的数据");
        }
        try {
            boolean success = courseService.removeByIds(ids);
            return AjaxResult.success("成功删除" + (success ? ids.size() : 0) + "条数据");
        } catch (Exception e) {
            log.error("批量删除课程失败，ids: {}", ids, e);
            return AjaxResult.error("删除失败：" + e.getMessage());
        }
    }

    @GetMapping("/export")
    @PreAuthorize("@ss.hasPerm('clues:course:export')")
    public void exportExcel(CourseDTO courseDTO, HttpServletResponse response) {
        //1. 查询需要导出的数据
        List<TbCourse> list = courseService.finList(courseDTO);
        ExcelUtil.exportExcel(list, "课程数据", TbCourse.class, response);
    }

}
